//
//  BBRawBlobView.m
//  BBTouch
//
//  Created by ben smith on 5/28/08.
//  This file is part of BBTouch.
//
//  BBTouch is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.

//  BBTouch is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.

//  You should have received a copy of the GNU Lesser General Public License
//  along with BBTouch.  If not, see <http://www.gnu.org/licenses/>.
// 
//  Copyright 2008 Ben Britten Smith ben@benbritten.com .
//

#import "BBRawBlobView.h"
#import "BBPixelBlob.h"
#import "NSView+BBViewAdditions.h"

// NOTE: This object has been obsoleted, see the BBSimpleEventView instead.

@implementation BBRawBlobView

@synthesize backgroundGradient;

-(void)awakeFromNib
{
	blobs = [[NSMutableArray alloc] init];	
	[self setupBackgroundGradient];
}

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
			blobs = [[NSMutableArray alloc] init];
			[self setupBackgroundGradient];
			// Initialization code here.
    }
    return self;
}

-(void)setBlobs:(NSArray*)blobArray
{
	[blobs removeAllObjects];
	// an array of blobs
	[blobs addObjectsFromArray:blobArray];
	[self setNeedsDisplay:YES];
}

- (void)drawRect:(NSRect)rect {
    // Drawing code here.
	// this could be done all with one transform, but for now, keep it simple
	[self.backgroundGradient drawInRect:self.bounds angle:90.0];

	[self drawText:@"Blob View" centeredAtPoint:NSMakePoint(NSMidX([self bounds]), 10)];
	
	NSRect blobBounds = NSZeroRect;
	NSEnumerator * enumerator = [blobs objectEnumerator];
	BBPixelBlob * pBlob;
	while ((pBlob = [enumerator nextObject])) {
		blobBounds = NSUnionRect([pBlob boundingRect], blobBounds);
	}	
	
	// now we want to offset and scale everything so that this rect takes up the 'whole'
	// view
	blobBounds = NSInsetRect(blobBounds, -20, -20);
	
	// we need to figure out which way to scale down the blob bounds rectangle
	// to get it to fit into the bounds rectangle
	// if it is wider than it is tall, 
	// try width first
	float scaleFactor = NSWidth([self bounds])/NSWidth(blobBounds);
	// now check the height fits too
	if (NSHeight(blobBounds) * scaleFactor > NSHeight([self bounds])) {
		// then we need to scale it down further.
		scaleFactor = NSHeight([self bounds])/NSHeight(blobBounds);
	}
	
	NSAffineTransform * translate = [NSAffineTransform transform];
	NSAffineTransform * scale = [NSAffineTransform transform];

	[translate translateXBy:-(NSMinX(blobBounds)) yBy:-(NSMinY(blobBounds))];
	
	[scale scaleBy:scaleFactor];		
	
	[scale concat];
	[translate concat];

	enumerator = [blobs objectEnumerator];
	while ((pBlob = [enumerator nextObject])) {
		[self drawBlob:pBlob];
	}	
}

-(void)drawBlob:(BBPixelBlob*)aBlob
{
	// make a pretty oval in a rectangle. oooh!
	NSRect blobRect = [aBlob boundingRect];
	[[NSColor greenColor] set];
	[NSBezierPath strokeRect:blobRect];
	// now draw all the pixels, this might be slooow
	NSArray * pixels = [aBlob pixels];
	NSArray * values = [aBlob values];
	int valueMin = [aBlob valueMin];
	int valueMax = [aBlob valueMax];
	int i;
	for (i = 0 ; i < [pixels count] ; i++) {
		float color = (float)[[values objectAtIndex:i] unsignedIntValue];
		color -= valueMin;
		color /= (valueMax - valueMin) ;
		[[NSColor colorWithDeviceWhite:color alpha:1.0] set];			
		NSPoint p = [[pixels objectAtIndex:i] pointValue];
		NSRectFill(NSMakeRect(p.x, p.y, 2, 2));
	}
}

- (BOOL)canBecomeKeyView
{
	return YES;	
}

- (BOOL)acceptsFirstResponder
{
	return YES;	
}

- (BOOL)becomeFirstResponder
{
	// need to make a note so I can draw a focus ring
	[self setNeedsDisplay:YES];
	return YES;
}

- (BOOL)resignFirstResponder
{
	// need to make a note so I can draw a focus ring
	[self setNeedsDisplay:YES];
	return YES;
}


-(IBAction)keyDown:(NSEvent*)theEvent
{
	if ([theEvent keyCode] == 53) {
		[[NSNotificationCenter defaultCenter] postNotificationName:@"BBEscapeKeyDownNotification" object:nil];
		return;		
	}
	if ([[theEvent charactersIgnoringModifiers] isEqualToString:@"f"]) {
		[[NSNotificationCenter defaultCenter] postNotificationName:@"BBFreezeFrameNotification" object:nil];
		return;		
	}
	
	[super keyDown:theEvent];
}

- (void)setupBackgroundGradient
{
	// create a basic gradient for the background of the view
	
	CGFloat red1   =    0.0 / 255.0;
	CGFloat green1 =   0.0 / 255.0;
	CGFloat blue1  =  0.0 / 255.0;
	
	CGFloat red2    =  40.0 / 255.0;
	CGFloat green2  =  40.0 / 255.0;
	CGFloat blue2   =  40.0 / 255.0;
	
	NSColor* gradientTop    = [NSColor colorWithCalibratedRed:red1 green:green1 blue:blue1 alpha:1.0];    
	NSColor* gradientBottom = [NSColor colorWithCalibratedRed:red2 green:green2 blue:blue2 alpha:1.0];
	
	NSGradient* gradient;
	gradient = [[NSGradient alloc] initWithStartingColor:gradientBottom endingColor:gradientTop];
	
	self.backgroundGradient = gradient;
	[gradient release];
}


@end
